package com.news.by.news;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.news.by.R;

public class Weather extends Activity{
	
	private TableLayout tl;
	private ArrayList<String> date_list = new ArrayList<String>();
	private ArrayList<String> temperature_list = new ArrayList<String>();
	private ArrayList<Bitmap> img_list = new ArrayList<Bitmap>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
		setContentView(R.layout.weather);
		
		new MyAsnClass(this).execute();		
		
	}
	
	protected void loadWeather(ArrayList<String> dateList, ArrayList<String> temperatureList, ArrayList<Bitmap> imgList){
		tl = (TableLayout)findViewById(R.id.tableLayout1);	
		TableRow tr = new TableRow(Weather.this);
		tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));      		
    		        		
    	try{
    			
    		for(int i = 0; i < dateList.size(); i++){        			
    			
    		    TableRow.LayoutParams param = new TableRow.LayoutParams();
    		    param.setMargins(1, 1, 2, 1);        		    
    			
    			tr = new TableRow(Weather.this);      
    			        			
    			TextView date = new TextView(Weather.this);
    			date.setGravity(Gravity.FILL);
    			date.setText(dateList.get(i));
				date.setBackgroundColor(Color.BLACK);
				date.setLayoutParams(param);
				date.setHeight(40);
				
				TextView temperature = new TextView(Weather.this);
				temperature.setGravity(Gravity.FILL);
				temperature.setText(temperatureList.get(i));
				temperature.setBackgroundColor(Color.BLACK);
				temperature.setLayoutParams(param);
				temperature.setHeight(40);
				
				ImageView image = new ImageView(Weather.this);
				
				image.setImageBitmap(imgList.get(i));
				image.setBackgroundColor(Color.BLACK);    				
				image.setLayoutParams(param);    				
				    			
				tr.addView(date);    				
				tr.addView(temperature);
				tr.addView(image);

				tl.addView(tr,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    		}    		
    		}catch (Exception e) {
				// TODO: handle exception    			
    			Toast.makeText(this, "Ошибка: " + e.getMessage(), Toast.LENGTH_LONG).show();
			}    		    		
	}
	
	public Bitmap getRemoteImage(final URL aURL) {
	    try {
	        final URLConnection conn = aURL.openConnection();
	        conn.connect();
	        final BufferedInputStream bis = new BufferedInputStream(
	                conn.getInputStream());
	        final Bitmap bm = BitmapFactory.decodeStream(bis);
	        bis.close();
	        return bm;
	    } catch (IOException e) {
	    	Toast.makeText(this, "Ошибка: " + e.getMessage(), Toast.LENGTH_LONG).show();
	    }
	    return null;
	}
	
	private class MyAsnClass extends AsyncTask<String, Boolean, Boolean>{
		private ProgressDialog dialog;
		 
		public MyAsnClass(Activity context) {
		    dialog = new ProgressDialog(context);
		}
		
		@Override
		protected void onPreExecute() {
		    this.dialog.setMessage("Загрузка. Ждите...");
		    this.dialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub					
			try{
				org.jsoup.nodes.Document doc = Jsoup.connect("http://pogoda.by/").get();
	    		Elements rows = doc.select("table#forecast");        		        		
	    		
				Element row = rows.get(0);
				
				for(int i = 1; i < row.child(0).children().size(); i++){
					date_list.add(row.child(0).child(i).text());
					temperature_list.add(row.child(2).child(i).text());
					
					String str_url = "http://pogoda.by/" + row.child(1).child(i).child(0).attr("src").toString();					
					URL url = new URL(str_url);		            
		            img_list.add(getRemoteImage(url));
				}
			}
			catch (Exception e) {
				// TODO: handle exception			
				Toast.makeText(Weather.this, "Ошибка: " + e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
			return true;
		}	
		
		@Override
		protected void onPostExecute(final Boolean success) {
		    if (dialog.isShowing()) {		    	
				loadWeather(date_list, temperature_list, img_list);
		        dialog.dismiss();		        
		    }		    
		}				
	}
}
